/*
 * @lc app=leetcode.cn id=938 lang=cpp
 *
 * [938] 二叉搜索树的范围和
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int rangeSumBST(TreeNode* root, int low, int high) {
        queue<TreeNode*> q;
        if(root)
            q.push(root);
        int ans = 0;
        while (!q.empty())
        {
            root = q.front();
            q.pop();
            if(root->val >= low && root->val <= high)
            {
                ans += root->val;
                if(root->left)
                    q.push(root->left);
                if(root->right)
                    q.push(root->right);
            }
            else if(root->val > high)
            {
                if(root->left)
                {
                    q.push(root->left);
                }
            }
            else
            {
                if(root->right)
                {
                    q.push(root->right);
                }
            }
        }
        return ans;
    }
};
// @lc code=end

